<template>
  <div class="my-orders-container">
    <el-card class="order-card">
      <template #header>
        <div class="card-header">
          <h2>我的订单</h2>
          <el-button type="primary" @click="$router.push('/createOrder')">创建新订单</el-button>
        </div>
      </template>
      
      <!-- 订单状态按钮组和搜索框在同一行 -->
      <div class="filter-row">
        <!-- 订单状态按钮组 -->
        <div class="status-buttons">
          <el-button 
            :type="activeStatus === 'all' ? 'primary' : 'default'"
            @click="handleStatusChange('all')"
          >
            全部订单
          </el-button>
          <el-button 
            :type="activeStatus === 'pending-pickup' ? 'primary' : 'default'"
            @click="handleStatusChange('pending-pickup')"
          >
            待揽收
          </el-button>
          <el-button 
            :type="activeStatus === 'pending' ? 'primary' : 'default'"
            @click="handleStatusChange('pending')"
          >
            待发货
          </el-button>
          <el-button 
            :type="activeStatus === 'shipping' ? 'primary' : 'default'"
            @click="handleStatusChange('shipping')"
          >
            运输中
          </el-button>
          <el-button 
            :type="activeStatus === 'delivering' ? 'primary' : 'default'"
            @click="handleStatusChange('delivering')"
          >
            待签收
          </el-button>
          <el-button 
            :type="activeStatus === 'completed' ? 'primary' : 'default'"
            @click="handleStatusChange('completed')"
          >
            已完成
          </el-button>
        </div>
        
        <!-- 搜索输入框组 -->
        <div class="search-inputs">
          <el-input 
            v-model="searchOrderNumber" 
            placeholder="订单号" 
            clearable
            @keyup.enter="handleSearch"
            style="width: 150px;"
          />
          <el-input 
            v-model="searchSenderName" 
            placeholder="寄件人" 
            clearable
            @keyup.enter="handleSearch"
            style="width: 120px;"
          />
          <el-input 
            v-model="searchReceiverName" 
            placeholder="收件人" 
            clearable
            @keyup.enter="handleSearch"
            style="width: 120px;"
          />
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </div>
      </div>
      
      <!-- 订单列表 -->
      <div class="order-list" v-if="orderList.length > 0">
        <el-table :data="orderList" stripe>
          <el-table-column prop="orderNumber" label="订单号" width="180"></el-table-column>
          <el-table-column prop="senderName" label="寄件人" width="120"></el-table-column>
          <el-table-column prop="receiverName" label="收件人" width="120"></el-table-column>
          <el-table-column prop="receiverAddress" label="收件地址" min-width="200"></el-table-column>
          <el-table-column prop="totalFee" label="费用" width="100">
            <template #default="scope">
              ¥{{ scope.row.totalFee }}
            </template>
          </el-table-column>
          <el-table-column prop="orderStatus" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.orderStatus)">
                {{ getStatusText(scope.row.orderStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="创建时间" width="180">
            <template #default="scope">
              {{ formatDateTime(scope.row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <el-button size="small" @click="viewOrderDetail(scope.row)">详情</el-button>
              <el-popconfirm
                v-if="canDeleteOrder(scope.row)"
                title="确定要删除此订单吗？删除后无法恢复！"
                @confirm="handleDeleteOrder(scope.row)"
                confirm-button-text="确定删除"
                cancel-button-text="取消"
                confirm-button-type="danger"
              >
                <template #reference>
                  <el-button 
                    size="small" 
                    type="danger" 
                    style="margin-left: 8px;"
                  >
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 分页 -->
      <div class="pagination" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      
      <!-- 空状态 -->
      <div class="empty-placeholder" v-if="orderList.length === 0 && !loading">
        <el-empty description="暂无订单数据"></el-empty>
      </div>
      
      <!-- 加载状态 -->
      <div class="loading" v-if="loading">
        <el-skeleton :rows="5" animated />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Search, Delete } from '@element-plus/icons-vue'
import { userApi, type DeliveryOrder, type ApiResponse } from '@/api/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserRole } from '@/router'

const activeStatus = ref('all')
const searchOrderNumber = ref('')
const searchSenderName = ref('')
const searchReceiverName = ref('')
const orderList = ref<DeliveryOrder[]>([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 获取当前用户角色
const currentUserRole = ref(getUserRole())

// 获取订单列表
const getOrderList = async () => {
  loading.value = true
  try {
    let response: ApiResponse
    
    // 根据不同状态调用不同接口
    switch (activeStatus.value) {
      case 'all':
        response = await userApi.getDeliveryOrderList(currentPage.value, pageSize.value)
        break
      case 'pending-pickup':
        // 待揽收状态使用全部订单接口，然后前端筛选状态为0的订单
        response = await userApi.getDeliveryOrderList(currentPage.value, pageSize.value)
        break
      case 'pending':
        response = await userApi.getDeliveryStatusList(currentPage.value, pageSize.value)
        break
      case 'shipping':
        response = await userApi.getDeliveryProcessingList(currentPage.value, pageSize.value)
        break
      case 'delivering':
        response = await userApi.getDeliveryDeliveryingList(currentPage.value, pageSize.value)
        break
      case 'completed':
        response = await userApi.getDeliveryCompletedList(currentPage.value, pageSize.value)
        break
      default:
        response = await userApi.getDeliveryOrderList(currentPage.value, pageSize.value)
    }
    
    console.log('订单列表响应:', response)
    
    // 处理响应数据
    if (response.code === 1 || response.code === 200) {
      // 兼容不同的响应格式，添加类型检查
      let data: any
      if (response.data && typeof response.data === 'object') {
        data = response.data
      } else if (response.msg && typeof response.msg === 'object') {
        data = response.msg
      } else {
        data = response
      }
      
      // 确保data是对象且有list属性
      if (data && typeof data === 'object' && Array.isArray(data.list)) {
        let filteredList = data.list
        
        // 如果是待揽收状态，需要筛选状态为0的订单
        if (activeStatus.value === 'pending-pickup') {
          filteredList = data.list.filter(order => order.orderStatus === 0)
        }
        
        orderList.value = filteredList
        total.value = activeStatus.value === 'pending-pickup' ? filteredList.length : (data.total || 0)
      } else {
        orderList.value = []
        total.value = 0
      }
    } else {
      ElMessage.error(response.message || '获取订单列表失败')
      orderList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
    orderList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 处理状态切换
const handleStatusChange = (status: string) => {
  activeStatus.value = status
  currentPage.value = 1
  // 清空搜索条件
  searchOrderNumber.value = ''
  searchSenderName.value = ''
  searchReceiverName.value = ''
  getOrderList()
}

// 处理搜索
const handleSearch = async () => {
  // 如果所有搜索条件都为空，则获取当前状态的订单列表
  if (!searchOrderNumber.value.trim() && !searchSenderName.value.trim() && !searchReceiverName.value.trim()) {
    getOrderList()
    return
  }
  
  loading.value = true
  try {
    const response = await userApi.selectDeliveryOrderList(
      searchOrderNumber.value.trim(),
      searchSenderName.value.trim(),
      searchReceiverName.value.trim(),
      currentPage.value,
      pageSize.value
    )
    
    console.log('搜索响应:', response)
    
    if (response.code === 1 || response.code === 200) {
      let data: any
      if (response.data && typeof response.data === 'object') {
        data = response.data
      } else if (response.msg && typeof response.msg === 'object') {
        data = response.msg
      } else {
        data = response
      }
      
      if (data && typeof data === 'object' && Array.isArray(data.list)) {
        orderList.value = data.list
        total.value = data.total || 0
      } else {
        orderList.value = []
        total.value = 0
      }
    } else {
      ElMessage.error(response.message || '搜索失败')
      orderList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败')
    orderList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 重置搜索
const handleReset = () => {
  searchOrderNumber.value = ''
  searchSenderName.value = ''
  searchReceiverName.value = ''
  currentPage.value = 1
  getOrderList()
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  // 如果有搜索条件，执行搜索，否则获取列表
  if (searchOrderNumber.value.trim() || searchSenderName.value.trim() || searchReceiverName.value.trim()) {
    handleSearch()
  } else {
    getOrderList()
  }
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  // 如果有搜索条件，执行搜索，否则获取列表
  if (searchOrderNumber.value.trim() || searchSenderName.value.trim() || searchReceiverName.value.trim()) {
    handleSearch()
  } else {
    getOrderList()
  }
}

// 查看订单详情
const viewOrderDetail = (order: DeliveryOrder) => {
  console.log('查看订单详情:', order)
  ElMessage.info('订单详情功能待实现')
}

// 判断是否可以删除订单
const canDeleteOrder = (order: DeliveryOrder) => {
  // 配送员不允许删除任何订单
  if (currentUserRole.value === 'courier') {
    return false
  }
  
  // 管理员和用户可以删除待揽收(0)和已完成(4)状态的订单
  return order.orderStatus === 0 || order.orderStatus === 4
}

// 处理删除订单
const handleDeleteOrder = async (order: DeliveryOrder) => {
  try {
    const response = await userApi.deleteDeliveryOrder(order.deliveryOrderId)
    
    if (response.code === 1 || response.code === 200) {
      ElMessage.success('订单删除成功')
      // 重新加载订单列表
      if (searchOrderNumber.value.trim() || searchSenderName.value.trim() || searchReceiverName.value.trim()) {
        handleSearch()
      } else {
        getOrderList()
      }
    } else {
      ElMessage.error(response.message || '删除订单失败')
    }
  } catch (error) {
    console.error('删除订单失败:', error)
    ElMessage.error('删除订单失败，请重试')
  }
}

// 获取状态文本
const getStatusText = (status: number) => {
  const statusMap: { [key: number]: string } = {
    0: '待揽收',
    1: '待发货',
    2: '运输中',
    3: '待签收',
    4: '已完成'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态标签类型
const getStatusType = (status: number) => {
  const typeMap: { [key: number]: string } = {
    0: 'danger',
    1: 'warning',
    2: 'primary',
    3: 'info',
    4: 'success'
  }
  return typeMap[status] || 'default'
}

// 格式化时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 组件挂载时获取数据
onMounted(() => {
  getOrderList()
})
</script>

<style scoped>
.my-orders-container {
  padding: 20px;
}

.order-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.filter-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  gap: 20px;
}

.status-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.search-inputs {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-shrink: 0;
}

.order-list {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

.empty-placeholder {
  margin: 60px 0;
}

.loading {
  margin: 20px 0;
}

@media (max-width: 1200px) {
  .filter-row {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .search-inputs {
    width: 100%;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
}
</style>